<template>
	<div>
		<el-dialog :title="dataForm.id ? '修改' : '添加'" :visible.sync="dialogVisible" :close-on-click-modal="false"
			width="40%" :before-close="handleClose">
			<el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="submitFun()"
				label-width="120px">
				<el-form-item label="角色名称" prop="roleName">
					<el-input v-model="dataForm.roleName" placeholder="角色名称"></el-input>
				</el-form-item>
				<el-form-item label="备注" prop="remark">
					<el-input v-model="dataForm.remark" placeholder="备注"></el-input>
				</el-form-item>
				<el-form-item size="mini" label="授权" :class="menuListChoose ? '' : 'is-error'" class="is-required">
					<el-tree :check-strictly="isCheck" :data="menuList" :props="menuListTreeProps" node-key="menuId"
						ref="menuListTree" :default-expand-all="false" show-checkbox>
					</el-tree>
					<div class="el-form-item__error" v-if="!menuListChoose">
						授权不能为空
					</div>
				</el-form-item>
				<el-form-item size="mini" label="微信菜单授权" :class="deviceListChoose ? '' : 'is-error'"
					class="is-required">
					<el-tree :check-strictly="isCheck" :data="deviceList" :props="deviceTreeProps" node-key="menuId"
						ref="deviceTree" :default-expand-all="false" show-checkbox>
					</el-tree>
					<div class="el-form-item__error" v-if="!deviceListChoose">
						微信菜单授权不能为空
					</div>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="dialogVisible = false">取消</el-button>
				<el-button type="primary" @click="submitFun()" :disabled='isDisabled'>确定</el-button>
			</span>
		</el-dialog>

	</div>
</template>

<script>
import { treeDataTranslate } from '../../../utils/treeDataTranslate.js'
export default {
	name: 'userAddorUpdata',
	emits: ["refreshDataList"],
	data() {
		var validatePassword = (rule, value, callback) => {
			if (!this.dataForm.userId && !/\S/.test(value)) {
				callback(new Error('密码不能为空'))
			} else {
				callback()
			}
		}
		var validateComfirmPassword = (rule, value, callback) => {
			if (this.dataForm.password !== value) {
				callback(new Error('确认密码与密码输入不一致'))
			} else {
				callback()
			}
		}
		return {
			dialogVisible: false,
			isCheck: false,
			visible: false,
			isDisabled: false,
			menuList: [],
			deviceList: [],
			menuListTreeProps: {
				label: 'name',
				children: 'children'
			},
			deviceTreeProps: {
				label: 'name',
				children: 'children'
			},
			dataForm: {
				id: 0,
				roleName: '',
				remark: '',
			},
			dataRule: {
				roleName: [
					{ required: true, message: '角色名称不能为空', trigger: 'blur' }
				],
			},
			tempKey: -666666,// 临时key, 用于解决tree半选中状态项不能传给后台接口问题. # 待优化
			tempKey1: -999999,
			menuListChoose: true,
			deviceListChoose: true,
		}
	},
	methods: {
		init(id) {
			this.dialogVisible = true;
			this.dataForm.id = id;
			this.$nextTick(() => {
				this.$refs.dataForm.resetFields();
				this.isDisabled = false;
				this.menuListChoose = true
				this.deviceListChoose = true
			})
			// 获取微信菜单列表
			this.Sevice({
				url: 'sys/wxMenu/list',
				method: 'get'
			}).then(res => {
				if (res && res.code == 200) {
					this.deviceList = treeDataTranslate(res.data, 'menuId');
				} else {
					this.deviceList = [];
				}
			}).catch(err => {
				console.log(err);
			})
			this.Sevice({
				url: '/sys/menu/list',
				method: 'get'
			}).then((res) => {
				console.log(res);
				if (res.code != 200) {
				} else {
					this.menuList = treeDataTranslate(res.data, 'menuId');
					console.log(this.menuList)
				}
			}).then(() => {
				this.visible = true
				this.$nextTick(() => {
					this.$refs['dataForm'].resetFields()
					this.$refs.menuListTree.setCheckedKeys([])
					this.$refs.deviceTree.setCheckedKeys([])
					this.isDisabled = false;
				})
			}).then(() => {
				console.log(id)
				if (!id) {
					//新增
				} else {
					this.isCheck = true;
					this.Sevice({
						url: "/sys/role/info/" + this.dataForm.id,
						method: 'get',
					}).then((res) => {
						console.log(res);
						if (res.code != 200) {
							// this.$message.error(res.data.msg)
						} else {
							this.dataForm.roleName = res.role.roleName
							this.dataForm.remark = res.role.remark
							var idx = res.role.menuIdList.indexOf(this.tempKey)
							if (idx !== -1) {
								// res.data.role.menuIdList.splice(idx, res.data.role.menuIdList.length - idx)
								res.role.menuIdList.splice(idx, 1)
							}
							this.$refs.menuListTree.setCheckedKeys(res.role.menuIdList)

							var idx1 = res.role.wxMenuIdList.indexOf(this.tempKey1)
							if (idx1 !== -1) {
								// res.data.role.menuIdList.splice(idx, res.data.role.menuIdList.length - idx)
								res.role.wxMenuIdList.splice(idx1, 1)
							}
							this.$refs.deviceTree.setCheckedKeys(res.role.wxMenuIdList)


							this.isCheck = false
						}
					})
				}
			})

		},
		//选择角色
		handRole(value) {
			console.log(value)
			this.dataForm.roleIdList.push(Number(value));
		},
		//关闭弹窗
		handleClose(done) {
			done();
		},
		//提交
		submitFun() {
			this.$refs['dataForm'].validate((valid) => {
				if (valid) {
					this.isDisabled = true;
					let urlApi = this.dataForm.id ? '/sys/role/update' : '/sys/role/save';
					if (this.dataForm.id == '') {
						this.isDisabled = true;
					}
					let menu = [].concat(this.$refs.menuListTree.getCheckedKeys(), [this.tempKey], this.$refs.menuListTree.getHalfCheckedKeys())
					let wxMenu = [].concat(this.$refs.deviceTree.getCheckedKeys(), [this.tempKey1], this.$refs.deviceTree.getHalfCheckedKeys())
					console.log(menu,wxMenu)
					if (menu.length<=1) {
						this.menuListChoose = false
						this.isDisabled = false;
						return false
					}else{
						this.menuListChoose = true
					}
					if (wxMenu.length<=1) {
						this.deviceListChoose = false
						this.isDisabled = false;
						return false
					}else{
						this.deviceListChoose = true
					}
					//提交表单
					this.Sevice({
						url: urlApi,
						method: 'post',
						data: {
							'roleId': this.dataForm.id || undefined,
							'roleName': this.dataForm.roleName,
							'remark': this.dataForm.remark,
							'menuIdList': [].concat(this.$refs.menuListTree.getCheckedKeys(), [this.tempKey], this.$refs.menuListTree.getHalfCheckedKeys()),
							'wxMenuIdList': [].concat(this.$refs.deviceTree.getCheckedKeys(), [this.tempKey1], this.$refs.deviceTree.getHalfCheckedKeys()),
						},
					}).then(res => {
						if (res && res.code == 200) {
							this.dialogVisible = false;
							this.$message({
								message: res.msg,
								type: 'success',
								duration: 1500,
								onClose: () => {
									this.$emit('getRolelist')
									this.isDisabled = false;
								}
							})
						} else {
							this.isDisabled = false;
						}
					}).catch(err => {
						console.log(err);
						this.isDisabled = false;
					})
				}
			})
		}
	}
}
</script>

<style></style>
